import UIKit
import FastSwiftSDK

protocol SelectionViewDelegate: AnyObject {
    func didSelectItem(_ item: String)
}

class SelectionView: FastView, UITableViewDelegate, UITableViewDataSource {

    weak var delegate: SelectionViewDelegate?
    
    private lazy var btn_select : FastButton = {
        let btn =  FastButton.init(imgName: "show_close");
        btn.title = "未选择设备"
        btn.click = { [weak self] in
            self?.toggleList()
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var tableView : UITableView = {
        let tableView =  UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isHidden = true // 初始状态隐藏
        tableView.backgroundColor = .lightGray
        self.addSubview(tableView)
        return  tableView
    } ()
    

    private var items:Array<String>  = []
    private var isListHidden = true
        
    func updateItems(devices:Array<XXDevice>){
        self.items.removeAll()
        for device in devices{
            let title = "\(device.type)-\(device.mac)"
            self.items.append(title)
        }
        self.tableView.reloadData()
    }
    
    override func layoutSubviews() {
        btn_select.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        tableView.snp.makeConstraints { make in
            make.top.equalTo(btn_select.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(200)
        }
    }
    
    private func toggleList() {
        isListHidden = !isListHidden
        tableView.isHidden = isListHidden
        if isListHidden == true{
            btn_select.image = kImage("show_close")
        }else{
            btn_select.image = kImage("show_open")
        }
    }
    
    // MARK: - TableView DataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
    
    // MARK: - TableView Delegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        btn_select.title = items[indexPath.row]
    }
}
